package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.zhijian.medical.dao.local.NgsSjpzqMapper;
import com.zhijian.medical.entity.dto.NgsSjpzqSjDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Ngs;
import com.zhijian.medical.entity.po.NgsSjpzq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.NgsSjpzqSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.NgsSjpzqSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.NgsSjpzqVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.NgsStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.NgsService;
import com.zhijian.medical.service.NgsSjpzqService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 二代测序-试剂配制区（片段化反应液及末端修复加A反应液配制）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-23 15:01:03
 */
@Slf4j
@Service
public class NgsSjpzqServiceImpl implements NgsSjpzqService {

    @Autowired
    private NgsSjpzqMapper mapper;

    @Autowired
    private NgsService ngsService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public NgsSjpzq selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public NgsSjpzq selectByNgsId(Long ngsId) {
        return mapper.selectByNgsId(ngsId);
    }

    @Override
    public NgsSjpzqVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByNgsId(Long ngsId) {
        mapper.deleteByNgsId(ngsId);
    }

    @Override
    public Long insert(NgsSjpzq ngsSjpzq) {
        Date now = new Date();
        ngsSjpzq.setCreateTime(now);
        ngsSjpzq.setUpdateTime(now);
        ngsSjpzq.setJcrq(DateUtil.formatDate(new Date()));
        ngsSjpzq.setSystmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setAzfzsop0xxpz(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        ngsSjpzq.setZdq(StatusEnum.NORMAL.getCode().byteValue());
        ngsSjpzq.setCjt(StatusEnum.NORMAL.getCode().byteValue());
        ngsSjpzq.setSjzyxqn(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setQjjzwxzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjpzq.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(ngsSjpzq) > 0 ? ngsSjpzq.getId() : 0L;
    }

    @Override
    public boolean update(NgsSjpzq ngsSjpzq) {
        Date now = new Date();
        ngsSjpzq.setUpdateTime(now);
        return mapper.updateByPrimaryKey(ngsSjpzq) != 0;
    }

    @Override
    public Integer count(NgsSjpzqSearchVo ngsSjpzqSearchVo) {
        return mapper.count(ngsSjpzqSearchVo);
    }

    @Override
    public List<NgsSjpzqVo> selectList(NgsSjpzqSearchVo ngsSjpzqSearchVo) {
        return mapper.selectList(ngsSjpzqSearchVo);
    }

    @Override
    public Page<NgsSjpzqVo> selectPage(NgsSjpzqSearchVo ngsSjpzqSearchVo) {
        //先直接查总数
        int count = count(ngsSjpzqSearchVo);
        //分页
        Page<NgsSjpzqVo> page = new Page<>(true, count, ngsSjpzqSearchVo.getPageNum(), ngsSjpzqSearchVo.getPageSize());
        ngsSjpzqSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<NgsSjpzqVo> responseVos = this.selectList(ngsSjpzqSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public NgsSjpzqVo selectVoByNgsId(Long ngsId) {
        NgsSjpzqVo ngsSjpzqVo = mapper.selectVoByNgsId(ngsId);
        if (Objects.isNull(ngsSjpzqVo)) {
            return null;
        }
        Ngs ngs = ngsService.selectById(ngsId);
        if (Objects.isNull(ngs)) {
            return null;
        }
        ngsSjpzqVo.setResult(ngs.getStatus() > NgsStatusEnum.SJPZQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        ngsSjpzqVo.setResultStr(ngs.getStatus() > NgsStatusEnum.SJPZQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());

        String sjData1 = ngsSjpzqVo.getSjData1();
        if (StringUtils.isNotBlank(sjData1)) {
            ngsSjpzqVo.setSjData1List(JsonUtil.toArray(sjData1, NgsSjpzqSjDto.class));
        }
        String sjData2 = ngsSjpzqVo.getSjData2();
        if (StringUtils.isNotBlank(sjData2)) {
            ngsSjpzqVo.setSjData2List(JsonUtil.toArray(sjData2, NgsSjpzqSjDto.class));
        }
        String sjData3 = ngsSjpzqVo.getSjData3();
        if (StringUtils.isNotBlank(sjData3)) {
            ngsSjpzqVo.setSjData3List(JsonUtil.toArray(sjData3, NgsSjpzqSjDto.class));
        }
        String sjData4 = ngsSjpzqVo.getSjData4();
        if (StringUtils.isNotBlank(sjData4)) {
            ngsSjpzqVo.setSjData4List(JsonUtil.toArray(sjData4, NgsSjpzqSjDto.class));
        }

        return ngsSjpzqVo;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(NgsSjpzqSaveOrUpdateVo ngsSjpzqSaveOrUpdateVo) {
        Long ngsId = ngsSjpzqSaveOrUpdateVo.getNgsId();
        Ngs ngs = ngsService.selectById(ngsId);
        AssertUtil.notNull(ngs, "此实验不存在或者已被删除");
        if (ngs.getStatus() < NgsStatusEnum.HSZBQ.getCode().byteValue()) {
            //修改实验的状态
            ngsService.updateByPrimaryKeySelective(Ngs.builder()
                    .id(ngsId)
                    .status(NgsStatusEnum.HSZBQ.getCode().byteValue())
                    .build());
        }
        List<NgsSjpzqSjDto> sjData1List = ngsSjpzqSaveOrUpdateVo.getSjData1List();
        if (CollectionUtil.isNotEmpty(sjData1List)) {
            ngsSjpzqSaveOrUpdateVo.setSjData1(JsonUtil.toString(sjData1List));
        }
        List<NgsSjpzqSjDto> sjData2List = ngsSjpzqSaveOrUpdateVo.getSjData2List();
        if (CollectionUtil.isNotEmpty(sjData2List)) {
            ngsSjpzqSaveOrUpdateVo.setSjData2(JsonUtil.toString(sjData2List));
        }
        List<NgsSjpzqSjDto> sjData3List = ngsSjpzqSaveOrUpdateVo.getSjData3List();
        if (CollectionUtil.isNotEmpty(sjData3List)) {
            ngsSjpzqSaveOrUpdateVo.setSjData3(JsonUtil.toString(sjData3List));
        }
        List<NgsSjpzqSjDto> sjData4List = ngsSjpzqSaveOrUpdateVo.getSjData4List();
        if (CollectionUtil.isNotEmpty(sjData4List)) {
            ngsSjpzqSaveOrUpdateVo.setSjData4(JsonUtil.toString(sjData4List));
        }
        NgsSjpzq ngsSjpzq = this.selectByNgsId(ngsId);
        NgsSjpzq dbParam = new NgsSjpzq();
        BeanUtils.copyProperties(ngsSjpzqSaveOrUpdateVo, dbParam);
        if (Objects.isNull(ngsSjpzq)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(ngsSjpzq.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .experimentProcessId(ngsId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(ngsId)
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .op(String.format("%s%s-%s", ngs.getName(), ngs.getProcessNumber(), NgsStatusEnum.SJPZQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}